package cc.core.ccequalizer

import android.content.Context
import android.content.DialogInterface
import android.util.Log
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.widget.SwitchCompat
import androidx.core.util.forEach
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.tabs.TabLayout
import kotlinx.android.synthetic.main.dialog_eq.*
import kotlin.concurrent.thread

class EqDialog : BottomSheetDialog {
    constructor(context: Context) : super(context, R.style.BottomSheetDialog)
    constructor(context: Context, theme: Int) : super(context, R.style.BottomSheetDialog)
    constructor(
        context: Context,
        cancelable: Boolean,
        cancelListener: DialogInterface.OnCancelListener?
    ) : super(context, cancelable, cancelListener)

    var curIndex = 0
    val eqContent: EqualizerViewHolder
    val yusheContent: YuSheVewHolder
    val reservbContent: YuSheVewHolder

    init {
        setContentView(R.layout.dialog_eq)
        eqContent = EqualizerViewHolder(vs)
        yusheContent = YuSheVewHolder(vs)
        reservbContent = YuSheVewHolder(vs)
        vs.setFactory {
            println("fuck")
            FrameLayout(context)
        }
        vs.setInAnimation(context, android.R.anim.slide_in_left)
        vs.setOutAnimation(context, android.R.anim.slide_out_right)
        (vs.currentView as ViewGroup).let {
            it.removeAllViews()
            it.addView(eqContent.getContent())
        }
        tabEq.setOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabSelected(tab: TabLayout.Tab) {
                val index = tab.position
                showTab(index)
            }
        })
    }

    fun showTab(index: Int) {
        (vs.currentView as ViewGroup).removeAllViews()
        (vs.nextView as ViewGroup).removeAllViews()
        val realContent: IEqDialogViewHolder =
            if (index == 0) {
                eqContent
            } else if (index == 1) {
                yusheContent.syncStatus()
                yusheContent
            } else {
                reservbContent
            }
        (vs.nextView as ViewGroup).addView(
            realContent.getContent(),
            ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                eqContent.getContent().height
            )
        )
        vs.showNext()
    }
}

class EqualizerViewHolder(val parent: ViewGroup) : IEqDialogViewHolder {
    val tag = "EqualizerViewHolder"
    val contentView =
        LayoutInflater.from(parent.context).inflate(
            R.layout.layout_equalizer,
            parent,
            false
        ) as ViewGroup
    val viewMap = SparseArray<SeekBar>()
    var bMin: Short = 0
    var bMax: Short = 0

    init {
        EqHolder.equalizer?.let { equalizer ->
            val count = equalizer.numberOfBands ?: 0
            val lf = LayoutInflater.from(parent.context)
            //            //负数
            bMin = equalizer.bandLevelRange?.get(0) ?: 0
            bMax = equalizer.bandLevelRange?.get(1) ?: 0
            val max =
                Math.abs(bMax.toInt()) + Math.abs(equalizer.bandLevelRange?.get(1)?.toInt() ?: 0)
            contentView.findViewById<SwitchCompat>(R.id.scEqEnable).also {
                it.isChecked = EqHolder.isEqEnable()
                it.text = if (it.isChecked) "均衡器已开启" else "均衡器已关闭"
                it.setOnCheckedChangeListener { buttonView, isChecked ->
                    thread {
                        var isSuccess = equalizer.setEnabled(isChecked) == 0
                        var tryCount = 0
                        while (!isSuccess && tryCount < 3) {
                            isSuccess = equalizer.setEnabled(isChecked) == 0
                            Thread.sleep(10)
                            tryCount++
                        }
                        Log.d(tag, "setEnable${equalizer.setEnabled(isChecked)}")
                        EqHolder.saveEq()
                    }
                    it.text = if (it.isChecked) "均衡器已开启" else "均衡器已关闭"
                }
            }

            for (brand in 0 until count) {
                val item = lf.inflate(R.layout.layout_eq_item, contentView, false)
                val seekBar = item.findViewById<SeekBar>(R.id.sb)
                seekBar.max = max
                seekBar.progress = equalizer.getBandLevel(brand.toShort()).toInt() - bMin
                seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                    override fun onProgressChanged(
                        seekBar: SeekBar?,
                        progress: Int,
                        fromUser: Boolean
                    ) {
                        if (fromUser) {
                            EqHolder.setBandLevel(
                                brand.toShort(),
                                (progress + bMin).toShort()
                            )
                        }
                    }

                    override fun onStartTrackingTouch(seekBar: SeekBar?) {
                    }

                    override fun onStopTrackingTouch(seekBar: SeekBar?) {
                    }
                })
                item.findViewById<TextView>(R.id.tvMax)?.text =
                    "${equalizer.getCenterFreq(brand.toShort()) / 1000}Hz"
                contentView.addView(item)
                viewMap.put(brand, seekBar)
            }
            EqHolder.presetChangedListener = object : PresetChangedListener {
                override fun changed() {
                    refreshLevel()
                }
            }
        }
        refreshLevel()
        if (EqHolder.isSupportBassBoost()) {
            BassBoostViewHolder(contentView).add()
        }
    }

    private fun refreshLevel() {
        EqHolder.equalizer?.let { equalizer ->
            viewMap.forEach { key, value ->
                value.progress = equalizer.getBandLevel(key.toShort()).toInt() - bMin
            }
        }
    }

    override fun add() {
        if (contentView.parent != null) {
            parent.addView(contentView)
        }
    }

    override fun getContent(): ViewGroup {
        return contentView
    }
}

class BassBoostViewHolder(private val parent: ViewGroup) : IEqDialogViewHolder {
    val contentView = LayoutInflater.from(parent.context).inflate(
        R.layout.layout_bassboost,
        parent,
        false
    ) as ViewGroup

    init {
        val seekBar = contentView.findViewById<SeekBar>(R.id.sbBassBoost) as SeekBar
        contentView.findViewById<SwitchCompat>(R.id.scBassBoost).let {
            it.isChecked = EqHolder.isBassBoostEnable()
            it.setOnCheckedChangeListener { buttonView, isChecked ->
                thread {
                    EqHolder.setBassBoostEnable(isChecked)
                    EqHolder.saveEq()
                }
                it.text = if (isChecked) "低音增强已开启" else "低音增强已关闭"
            }
        }
        seekBar.let {
            it.max = 1000
            it.progress = EqHolder.bassBoost?.roundedStrength?.toInt() ?: 0
            it.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(
                    seekBar: SeekBar?,
                    progress: Int,
                    fromUser: Boolean
                ) {
                    EqHolder.setBassBoostStrength(progress.toShort())
                }

                override fun onStartTrackingTouch(seekBar: SeekBar?) {
                }

                override fun onStopTrackingTouch(seekBar: SeekBar?) {
                }

            })
        }
    }

    override fun add() {
        if (contentView.parent == null) {
            parent.addView(contentView)
        }
    }

    override fun getContent(): ViewGroup {
        return contentView
    }
}

interface IEqDialogViewHolder {
    fun add()
    fun getContent(): ViewGroup
}